import axios from 'axios'
import { getToken } from '@/utils/auth'
import store from '@/store/index'
import { Message } from 'element-ui'
import router from '@/router/index'
import { Loading } from 'element-ui'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/api',
  timeout: 10000 // request timeout
})
let loadingInstance
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 显示loading
    loadingInstance = Loading.service({ text: '拼命加载中'
    })
    const token = getToken()
    if (token) {
      config.headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': `Bearer ${token}`
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    loadingInstance.close()

    return response.data
  },
  error => {
    loadingInstance.close()

    console.log(error.response.data.code)
    if (error.response.data.code === 40001) {
      Message.error('登录过期')
      router.push('/login')
      // 删除vuex数据token
      store.commit('user/delToken')
    }
    if (error.response) {
      Message.error(error.response.data.msg)
    }
    return Promise.reject(error)
  }
)

export default service
